#define _CRT_SECURE_NO_WARNINGS 1
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define endl '\n'
int m, n, ans;
int lst[510];
int mach[30][100010];
int step[30];
int last_time[30];

struct node {
	int id, cost;
}a[30][30];

int main() {
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	cin >> m >> n;
	for (int i = 1; i <= m * n; i++) cin >> lst[i];
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			cin >> a[i][j].id;
		}
	}
	for (int i = 1; i <= n; i++) {
		for (int j = 1; j <= m; j++) {
			cin >> a[i][j].cost;
		}
	}
	for (int i = 1; i <= m * n; i++) {
		int now = lst[i];
		step[now]++;
		int id = a[now][step[now]].id, cost = a[now][step[now]].cost;
		int s = 0;
		for (int j = last_time[now] + 1; ; j++) {
			if (mach[id][j] == 0) {
				s++;
			}else {
				s = 0;
			}
			if (s == cost) {
				for (int k = j - cost + 1; k <= j; k++) {
					mach[id][k] = 1;
				}
				if (j > ans) ans = j;
				last_time[now] = j;
				break;
			}
		}
	}
	cout << ans << endl;
	return 0;
}